<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="UTF-8">
    <title th:text="${#session.getAttribute('title')}">Title</title>
    <link th:href="@{/css/user/record.css}" rel="stylesheet" type="text/css" media="screen,print"/>
    <link th:href="@{/css/footer.css}" rel="stylesheet" type="text/css" media="screen,print"/>
    <script th:src="@{/webjs/jquery-1.10.1.min.js}" type="text/javascript"></script>
    <link th:href="@{/webcss/bootstrap.css}" rel="stylesheet" type="text/css" media="screen,print"/>
    <script th:src="@{/webjs/bootstrap.js}" type="text/javascript"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
          integrity="sha384-..." crossorigin="anonymous">
</head>
<style>

    /* 自定义样式 */
    .custom-button {
        margin-right: 5px;
    }
</style>
<body>
<div class="container">
    <h1 th:text="${#session.getAttribute('title')}"></h1>
    <h1 th:text="'积分操作记录'"></h1>
    <p>
        <span th:text="'您目前可用积分为：'">, 您目前可用积分为：</span>
        <span th:text="${#session.getAttribute('point')}" class="highlight-blue">未获取到积分</span><br>
    </p>
    <!-- 在现有HTML中添加一个表单，用于选择年和月 -->
    <form id="dateQueryForm" class="d-flex align-items-center mb-3">
        <div class="me-auto">
            <label for="year" class="visually-hidden">年份:</label>
            <input type="number" id="year" name="year" min="1900" max="2100" value="当前年份" class="form-control me-2" placeholder="年份">
            <br>
            <label for="month" class="visually-hidden">月份:</label>
            <select id="month" name="month" class="form-control me-2">
                <option th:each="m : ${#numbers.sequence(1,12)}" th:value="${m}" th:text="${m < 10 ? ('0' + m) : m}"></option>
            </select>
        </div>
        <br>
        <button type="button"  onclick="queryByDate()" class="btn btn-primary">查询</button>
        <!-- 导出 -->
        <div style="margin-left: 5px;" class="btn-group" role="group" aria-label="Button group with nested dropdown">
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                    导出
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" id="exportModalByMonth">本月导出</a></li>
                    <li><a class="dropdown-item" data-bs-toggle="modal"  data-bs-target="#exportModal" >多月导出</a></li>
                    <li><a class="dropdown-item" data-bs-toggle="modal"  data-bs-target="#multipleExportModalByYear">多年导出</a></li>
                </ul>
            </div>
        </div>
    </form>
    <br>
    <br>
    <table id="recordsTable">
        <thead>
        <tr>
            <th>操作人</th>
            <th>类型</th>
            <th>操作积分</th>
            <th>操作前积分</th>
            <th>操作后积分</th>
            <th>操作时间</th>
            <th>备注</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="record:${records}">
            <td th:text="${record.operator}"></td>
            <td>
                <span th:if="${record.operationType == 1}"
                      th:text="减少" class="highlight-red">
             </span>
                <span th:if="${record.operationType == 2}"
                      th:text="增加" class="highlight-green">
             </span>
            </td>
            <td>
             <span th:if="${record.operationType == 1}"
              th:text="'- ' + ${record.operatorPoints}" class="highlight-red">
             </span>
             <span th:if="${record.operationType == 2}"
                      th:text="'+' + ${record.operatorPoints}" class="highlight-green">
             </span>
            </td>
            <td th:text="${record.oldPoints}"></td>
            <td th:text="${record.newPoints}"></td>
            <td><span th:text="${#dates.format(record.operationTime, 'yyyy/MM/dd HH:mm')}"></span></td>
            <td th:text="${record.notes}"></td>
        </tr>
        </tbody>
    </table>
</div>
<!-- 模态框 -->
<div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">选择导出时间范围（如需导出01.01的数据，请将结束时间选择到01.02）</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="exportForm">
                    <div class="mb-3">
                        <label for="startDate" class="form-label">开始时间</label>
                        <input type="date" class="form-control" id="startDate" name="startDate">
                    </div>
                    <div class="mb-3">
                        <label for="endDate" class="form-label">结束时间</label>
                        <input type="date" class="form-control" id="endDate" name="endDate">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmExport">确认</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="multipleExportModalByYear" tabindex="-1" aria-labelledby="multipleExportModalLabelByYear"
     aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="multipleExportModalLabelByYear">选择导出时间范围（如填2023-2024则导出为2023.01.01到2024.01.01）</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="startYear">开始年份:</label>
                        <input type="number" class="form-control" id="startYear" min="1900" max="2100">
                    </div>
                    <div class="form-group">
                        <label for="endYear">结束年份:</label>
                        <input type="number" class="form-control" id="endYear" min="1900" max="2100">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmExportButtonByYear">确认导出</button>
            </div>
        </div>
    </div>
</div>
<footer class="footer fixed-bottom">
    <div class="footer-links d-flex justify-content-center">
        <a href="toIndex" class="footer-link"><i class="fas fa-trophy"></i> 排行榜</a>
        <a href="toRecord" class="footer-link active"><i class="fas fa-history"></i> 积分记录</a>
        <a href="toUpdate" class="footer-link"><i class="fas fa-user"></i> 修改密码</a>
    </div>
</footer>
<label for="userId"></label><input style="display: none" id="userId" th:value="${#session.getAttribute('user').userId}">
</body>
<script>
    function queryByDate() {
        var year = document.getElementById('year').value;
        var month = document.getElementById('month').value;

        $.ajax({
            url: '/findByMonth',
            type: 'POST',
            data: { year: year, month: month },
            success: function(data) {
                $('#recordsTable tbody').empty();

                data.forEach(function(record) {
                    var row = '<tr>';
                    row += '<td>' + record.operator + '</td>';
                    row += '<td><span class="' + (record.operationType === 1 ? 'highlight-red' : 'highlight-green') + '">' + (record.operationType === 1 ? '减少' : '增加') + '</span></td>';
                    row += '<td><span class="' + (record.operationType === 1 ? 'highlight-red' : 'highlight-green') + '">' + (record.operationType === 1 ? '- ' : '+') + record.operatorPoints + '</span></td>';
                    row += '<td>' + record.oldPoints + '</td>';
                    row += '<td>' + record.newPoints + '</td>';
                    row += '<td>' + formatDateTime(record.operationTime) + '</td>';
                    row += '<td>' + record.notes + '</td>';
                    row += '</tr>';
                    $('#recordsTable tbody').append(row);
                });
            },
            error: function(error) {
                console.error('Error fetching records:', error);
            }
        });

        function formatDateTime(isoString) {
            var date = new Date(isoString);
            return date.toLocaleString('default', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'});
        }
    }
</script>
<script>
    document.getElementById('year').value = new Date().getFullYear();
</script>
<script>
    // JavaScript
    $(document).ready(function() {

        function formatDate(dateStr) {
            var date = new Date(dateStr);
            var year = date.getFullYear();
            var month = ('0' + (date.getMonth() + 1)).slice(-2); // +1 因为getMonth()是从0开始的
            var day = ('0' + date.getDate()).slice(-2);
            return year + month + day;
        }
        // 获取当前日期
        const currentDate = new Date();
        // 获取当前月份的第一天
        const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
        // 获取当前月份的最后一天
        const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

        var userId=$('#userId').val();

        $('#confirmExport').click(function() {
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            if (startDate && endDate) {
                exportRecords(userId,startDate, endDate);
            } else {
                alert('请选择有效的开始和结束时间！');
            }
        });
        $('#exportModalByMonth').click(function() {
            exportRecords(userId,firstDayOfMonth, lastDayOfMonth);
        });
        // 确认导出按钮
        $('#confirmExportButtonByYear').click(function () {
            var startDate = $('#startYear').val();
            var endDate = $('#endYear').val();
            if (startDate && endDate) {
                window.open('/exportRecords?startDate=' + startDate+'0101' + '&endDate=' + endDate+'0101'+ '&userId=' + userId);
                $('#multipleExportModalByYear').modal('hide');
            } else {
                alert("请选择有效的时间范围并至少选择一名用户！");
            }
        });
        function exportRecords(userId,startDate, endDate) {
            window.open('/exportRecords?startDate=' + formatDate(startDate) + '&endDate=' + formatDate(endDate)+ '&userId=' + userId);
        }

    });
</script>
</html>